<template>
  <div id="projectMarage">
    <div id="mainBox">
      <div id="boxTit">
        <span
          v-if="mid != null"
          class="tit"
        >修改模板</span>
        <span
          v-else
          class="tit"
        >添加模板</span>
      </div>
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
      >
        <el-form-item
          ref="name"
          label="模板名称"
        >
          <el-input v-model="form.name"/>
        </el-form-item>
        <div id="areaBox">
          <div class="in-coder-panel">
            <textarea
              ref="textarea"
              v-model="code"
            />
            <el-select
              v-model="mode"
              class="code-mode-select"
              @change="changeMode"
            >
              <el-option
                v-for="mode in modes"
                :key="mode.value"
                :label="mode.label"
                :value="mode.value"
              />
            </el-select>
          </div>
        </div>
        <el-form-item label="附加值">
          <div>
            <div id="tit">
              <div><span>名称</span></div>
              <div><span>路径</span></div>
              <div class="pro"><span>文件</span></div>
              <div class="addbtn">
                <i
                  class="el-icon-circle-plus-outline"
                  @click="appends"
                />
              </div>
            </div>
            <div
              v-for="(item,index) in arrays"
              ref="arrays"
              :key="index"
              class="subjoin"
            >
              <div class="sub">
                <el-input v-model="item.name"/>
              </div>
              <div class="sub">
                <el-input v-model="item.classPath"/>
              </div>
              <div class="sub pro">
                <div
                  v-if="item.filePath != '' "
                  class="btn"
                >
                  <el-popover
                    :content="item.filePath"
                    placement="top-start"
                    trigger="hover"
                  >
                    <i
                      slot="reference"
                      class="el-icon-circle-check"
                    />
                  </el-popover>
                </div>
                <div
                  v-else
                  class="btn"
                >
                  <i class="el-icon-circle-plus-outline"/>
                  <input
                    id="uploads"
                    ref="file"
                    type="file"
                    name=""
                    @change="upload(index)"
                  >
                </div>
                <div
                  class="closenBtn"
                  @click="closenBtn(index)"
                >
                  <i class="el-icon-circle-close"/>
                </div>
              </div>
              <div
                class="closenSubjoin"
                @click="closenSubjoin(index)"
              >
                <i class="el-icon-error"/>
              </div>
            </div>
          </div>

        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="form.templateDesc"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button
          class="next"
          @click="onSubmit"
        >提交</el-button>
        <el-button
          class="back"
          @click="onBack"
        >取消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { gtmSave, gtmDesc, gtmList } from '@/api/page'
// 引入全局实例
import _CodeMirror from 'codemirror'

// 核心样式
import 'codemirror/lib/codemirror.css'
// 引入主题后还需要在 options 中指定主题才会生效
import 'codemirror/theme/cobalt.css'

// 需要引入具体的语法高亮库才会有对应的语法高亮效果
// codemirror 官方其实支持通过 /addon/mode/loadmode.js 和 /mode/meta.js 来实现动态加载对应语法高亮库
// 但 vue 貌似没有无法在实例初始化后再动态加载对应 JS ，所以此处才把对应的 JS 提前引入
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/css/css.js'
import 'codemirror/mode/xml/xml.js'
import 'codemirror/mode/clike/clike.js'
import 'codemirror/mode/markdown/markdown.js'
import 'codemirror/mode/python/python.js'
import 'codemirror/mode/r/r.js'
import 'codemirror/mode/shell/shell.js'
import 'codemirror/mode/sql/sql.js'
import 'codemirror/mode/swift/swift.js'
import 'codemirror/mode/vue/vue.js'

const CodeMirror = window.CodeMirror || _CodeMirror

export default {
  data() {
    return {
      form: {
        name: '',
        desc: '',
        code: ''
      },
      data: {
        current: 1,
        size: 5,
        condition: {
          templateType: 'GENERATOR'
        }
      },
      arrays: [],
      mid: '',
      items: '',
      // 内部真实的内容
      code: '',
      // 默认的语法类型
      mode: 'javascript',
      // 编辑器实例
      coder: null,
      // 默认配置
      options: {
        // 缩进格式
        tabSize: 2,
        // 主题，对应主题库 JS 需要提前引入
        theme: 'cobalt',
        // 显示行号
        lineNumbers: true,
        line: true
      },
      // 支持切换的语法高亮类型，对应 JS 已经提前引入
      // 使用的是 MIME-TYPE ，不过作为前缀的 text/ 在后面指定时写死了
      modes: [
        {
          value: 'css',
          label: 'CSS'
        },
        {
          value: 'javascript',
          label: 'Javascript'
        },
        {
          value: 'html',
          label: 'XML/HTML'
        },
        {
          value: 'x-java',
          label: 'Java'
        },
        {
          value: 'x-objectivec',
          label: 'Objective-C'
        },
        {
          value: 'x-python',
          label: 'Python'
        },
        {
          value: 'x-rsrc',
          label: 'R'
        },
        {
          value: 'x-sh',
          label: 'Shell'
        },
        {
          value: 'x-sql',
          label: 'SQL'
        },
        {
          value: 'x-swift',
          label: 'Swift'
        },
        {
          value: 'x-vue',
          label: 'Vue'
        },
        {
          value: 'markdown',
          label: 'Markdown'
        }
      ]
    }
  },
  mounted() {
    this.mid = localStorage.getItem('mid')
    if (this.mid != null) {
      var arr = {
        id: this.mid,
        templateType: 'GENERATOR'
      }
      gtmDesc(arr)
        .then(response => {
          if (response.data.code == 'SUCCESS') {
            this.form = response.data.data
            this.code = response.data.data.varConsole
            this._initialize()

            if (response.data.data.sources == undefined) {
              this.arrays = []
            } else {
              this.arrays = response.data.data.sources
            }
            if (this.form.templateDesc == 'undefined') {
              this.form.templateDesc = ''
            } else {
              this.form.templateDesc = response.data.data.templateDesc
            }
          } else {
            alert(response.data.message)
          }
        })
        .catch(error => {
          // alert(error.response.data.message);
        })
    } else {
      this._initialize()
    }
  },
  methods: {
    // 初始化
    _initialize() {
      console.log('123')
      // 初始化编辑器实例，传入需要被实例化的文本域对象和默认配置
      this.coder = CodeMirror.fromTextArea(this.$refs.textarea, this.options)
      console.log(this.coder, '1')
      // 编辑器赋值
      this.coder.setValue(this.code)
      console.log(this.code, '2')

      // 支持双向绑定
      this.coder.on('change', coder => {
        this.code = coder.getValue()

        if (this.$emit) {
          this.$emit('input', this.code)
        }
      })

      // 尝试从父容器获取语法类型
      if (this.language) {
        // 获取具体的语法类型对象
        const modeObj = this._getLanguage(this.language)

        // 判断父容器传入的语法是否被支持
        if (modeObj) {
          this.mode = modeObj.label
        }
      }
    },
    // 获取当前语法类型
    _getLanguage(language) {
      // 在支持的语法类型列表中寻找传入的语法类型
      return this.modes.find(mode => {
        // 所有的值都忽略大小写，方便比较
        const currentLanguage = language.toLowerCase()
        const currentLabel = mode.label.toLowerCase()
        const currentValue = mode.value.toLowerCase()

        // 由于真实值可能不规范，例如 java 的真实值是 x-java ，所以讲 value 和 label 同时和传入语法进行比较
        return (
          currentLabel === currentLanguage || currentValue === currentLanguage
        )
      })
    },
    // 更改模式
    changeMode(val) {
      // 修改编辑器的语法配置
      this.coder.setOption('mode', `text/${val}`)

      // 获取修改后的语法
      const label = this._getLanguage(val).label.toLowerCase()

      // 允许父容器通过以下函数监听当前的语法值
      this.$emit('language-change', label)
    },
    onSubmit() {
      var _this = this
      _this.req()

      const postData = new FormData()
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }

      postData.append('name', _this.form.name)
      postData.append('templateDesc', _this.form.templateDesc)
      postData.append('templateType', 'GENERATOR')
      postData.append('varConsole', _this.code)

      if (this.mid != null) {
        postData.append('id', this.mid)
      }

      for (var i = 0; i < _this.arrays.length; i++) {
        if (this.arrays[i].pro == undefined) {
          postData.append(
            'sources[' + i + '].filePath',
            this.arrays[i].filePath
          )
        } else {
          postData.append('sources[' + i + '].filePath', '')
          if (this.arrays[i].filePath == '') {
            alert('请选择文件')
            return
          }
        }
        postData.append('sources[' + i + '].name', _this.arrays[i].name)
        postData.append(
          'sources[' + i + '].classPath',
          _this.arrays[i].classPath
        )
        postData.append(i, this.arrays[i].pro)
      }
      if (_this.form.name) {
        gtmSave(postData, config)
          .then(response => {
            if (response.data.code == 'SUCCESS') {
              if (this.mid != null) {
                localStorage.removeItem('mid')
              }
              this.openFullScreen()
              setTimeout(() => {
                this.loading.close()
                this.$router.push('/project/index')
              }, 1000)
            } else {
              alert(response.data.message)
            }
          })
          .catch(error => {
            alert(error.response.data.message)
          })
      }
    },
    appends() {
      var arrObj = { name: '', classPath: '', pro: {}, filePath: '' }
      this.arrays.push(arrObj)
    },
    openFullScreen() {
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    upload(index) {
      var event = window.event || arguments[0]
      var uplist = event.target.files
      // console.log(uplist[0].size/1000)
      // console.log((Math.round(uplist[0].size * 100 /1024 /1024) /100).toString()+"M")
      for (var i = 0; i < this.arrays.length; i++) {
        this.arrays[index].pro = uplist[0]
        this.arrays[index].filePath = uplist[0].name
      }
    },
    closenSubjoin(index) {
      this.arrays.splice(index, 1)
    },
    closenBtn(index) {
      this.arrays[index].filePath = ''
      this.arrays[index].pro = {}
    },
    onBack() {
      localStorage.removeItem('mid')
      this.$router.push('/project/index')
    },
    req() {
      if (this.form.name == '') {
        this.$refs.name.$el.childNodes[0].style.color = 'red'
        this.$refs.name.$el.childNodes[1].childNodes[0].childNodes[1].style.borderColor =
          'red'
      } else {
        this.$refs.name.$el.childNodes[0].style.color = '#606266'
        this.$refs.name.$el.childNodes[1].childNodes[0].childNodes[1].style.borderColor =
          '#c0c4cc'
      }

      for (var j = 0; j < this.arrays.length; j++) {
        if (
          this.$refs.arrays[j].childNodes[0].childNodes[0].childNodes[1]
            .value == ''
        ) {
          this.$refs.arrays[
            j
          ].childNodes[0].childNodes[0].childNodes[1].style.borderColor = 'red'
        } else {
          this.$refs.arrays[
            j
          ].childNodes[0].childNodes[0].childNodes[1].style.borderColor =
            '#c0c4cc'
        }
        if (
          this.$refs.arrays[j].childNodes[2].childNodes[0].childNodes[1]
            .value == ''
        ) {
          this.$refs.arrays[
            j
          ].childNodes[2].childNodes[0].childNodes[1].style.borderColor = 'red'
        } else {
          this.$refs.arrays[
            j
          ].childNodes[2].childNodes[0].childNodes[1].style.borderColor =
            '#c0c4cc'
        }
        if (this.form.name != '') {
          if (
            this.$refs.arrays[j].childNodes[0].childNodes[0].childNodes[1]
              .value != ''
          ) {
            if (
              this.$refs.arrays[j].childNodes[2].childNodes[0].childNodes[1]
                .value != ''
            ) {
            } else {
              return true
            }
          } else {
            return true
          }
        } else {
          return true
        }
      }
    }
  }
}
</script>
<style>
#projectMarage .el-input {
  width: 500px;
}
#projectMarage .el-textarea {
  width: 500px;
}
#projectMarage .subjoin {
  height: 40px;
  width: 500px;
}
#projectMarage .subjoin .el-input {
  width: 100px;
}
#projectMarage .el-input__inner {
  padding: 0 10px;
}
#projectMarage .sub {
  position: relative;
  float: left;
  width: 150px;
  height: 40px;
  border-bottom: 1px solid #ccc;
}
#projectMarage .sub .el-input__inner {
  height: 28px;
}

#projectMarage .sub .el-button--medium {
  padding: 3px 10px;
}
#projectMarage .sub .el-button {
  width: 100px;
  height: 28px;
}
#projectMarage #uploads {
  position: absolute;
  width: 30px;
  height: 36px;
  opacity: 0;
  left: 0;
  top: 0;
}
#projectMarage #tit {
  width: 530px;
  height: 30px;
  position: relative;
}
#projectMarage #tit div {
  width: 150px;
  height: 28px;
  line-height: 28px;
  float: left;
  border-bottom: 1px solid #ccc;
}
#projectMarage #tit div span {
  margin-left: 5px;
}
#projectMarage #tit .pro {
  width: 180px;
}
#projectMarage .closenSubjoin {
  color: crimson;
  position: absolute;
  left: -30px;
  font-size: 20px;
}
#projectMarage .btn {
  position: relative;
  text-align: center;
  width: 30px;
  color: aqua;
  font-size: 20px;
  float: left;
}
#projectMarage .closenBtn {
  color: cornflowerblue;
  text-align: center;
  width: 30px;
  font-size: 20px;
  float: left;
}
#projectMarage .el-form {
  margin: 90px 150px;
  margin-bottom: 20px;
}
#projectMarage #mainBox {
  margin-left: 15px;
  margin-top: 15px;
  width: 100%;
  border: 1px solid #623f18;
}
#projectMarage #mainBox #boxTit {
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #623f18;
}
#projectMarage #mainBox #boxTit .tit {
  margin-left: 20px;
  font-size: 20px;
  color: #623f18;
  line-height: 40px;
}
#projectMarage #mainBox .btns {
  text-align: center;
  border-top: 1px solid #e5e5e5;
  padding-top: 10px;
  padding-bottom: 10px;
  background: #f5f5f5;
}
#projectMarage #mainBox .btns .el-button {
  margin-right: 30px;
}
#projectMarage .next {
  background: #623f18;
  color: #fff;
}
#projectMarage .back {
  border-color: #623f18;
  color: #623f18;
}

#projectMarage .addbtn {
  width: auto;
  position: absolute;
  right: 0;
  top: 0;
  font-size: 20px;
}
#projectMarage .addbtn i {
  cursor: pointer;
}
#projectMarage #areaBox {
  position: relative;
  border: 1px solid #623f18;
}
#projectMarage #areaBox .code-mode-select {
  position: absolute;
  z-index: 2;
  right: 10px;
  top: 20px;
}
#projectMarage #areaBox .el-input {
  width: 120px;
}
</style>
